package database

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/spf13/viper"
	"time"
)

var Db *sql.DB

func DbInit() bool {
	config := viper.New()
	config.AddConfigPath("./config/")
	config.SetConfigName("db")
	config.SetConfigType("ini")
	err := config.ReadInConfig()
	if err != nil {
		fmt.Println(err)
		return false
	}
	dataSource := fmt.Sprintf("%s:%s@(%s:%s)/%s?charset=utf8",
		config.GetString("mysql.user"),
		config.GetString("mysql.password"),
		config.GetString("mysql.host"),
		config.GetString("mysql.port"),
		config.GetString("mysql.database"),
	)
	Db, _ = sql.Open("mysql", dataSource)
	Db.SetMaxOpenConns(2000)
	Db.SetMaxIdleConns(1000)
	Db.SetConnMaxLifetime(time.Minute * 60)
	err = Db.Ping()
	if err != nil {
		fmt.Println("Ping错误")
		fmt.Println(err)
		return false
	}
	return true
}
